<template>
  <div class="p-6 max-w-6xl mx-auto">
    <h1 class="text-2xl font-bold mb-4">路由管理</h1>

    <div class="mb-4 space-y-2">
      <label class="block">管理员密钥（只在本地保存于浏览器）</label>
      <div class="flex gap-2">
        <input v-model="adminKeyInput" type="password" class="border px-2 py-1 flex-1" placeholder="输入管理员密钥" />
        <button @click="saveKey" class="bg-blue-600 text-white px-3 py-1 rounded">保存并登录</button>
        <button @click="clearKey" class="bg-gray-200 px-3 py-1 rounded">登出</button>
      </div>
      <div v-if="!isAuthenticated" class="text-sm text-red-600">未认证。请输入有效密钥并保存。</div>
    </div>

    <div v-if="isAuthenticated">
      <!-- Route Management (Admin only) -->
      <div class="mt-8 bg-white border rounded p-4 mx-4 md:mx-0">
        <h2 class="text-lg font-semibold mb-3">路由访问管理</h2>
        <div v-if="loadingRoutes" class="text-sm text-gray-500">加载中…</div>
        <div v-else class="space-y-2">
          <div v-for="r in adminRoutes" :key="r.path" class="flex items-center justify-between">
            <div>
              <div class="font-medium">{{ r.path }}</div>
              <div class="text-sm text-gray-500">{{ r.allowed ? '允许访问' : '禁止访问' }}</div>
            </div>
            <div>
              <button @click="toggleRoute(r)" class="px-3 py-1 border rounded">
                {{ r.allowed ? '禁止' : '允许' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
definePageMeta({ middleware: 'admin-access' })
import { ref, computed, onMounted } from 'vue'

const adminKeyInput = ref('')
const adminKey = ref('')
const isAuthenticated = computed(() => !!adminKey.value)

// 已在上方定义页面元信息与导入（避免重复导入）
// 路由管理状态
const adminRoutes = ref([])
const loadingRoutes = ref(false)

async function fetchRoutes() {
  try {
    loadingRoutes.value = true
    const key = typeof window !== 'undefined' ? localStorage.getItem('admin_key') : ''
    const res = await $fetch('/api/admin-routes', { method: 'GET', headers: { 'x-admin-key': key || '' } }).catch(() => null)
    if (res && Array.isArray(res.routes)) {
      adminRoutes.value = res.routes
    }
  } finally {
    loadingRoutes.value = false
  }
}

async function toggleRoute(r) {
  const key = typeof window !== 'undefined' ? localStorage.getItem('admin_key') : ''
  try {
    await $fetch('/api/admin-routes', { method: 'POST', headers: { 'x-admin-key': key || '' }, body: { path: r.path, allowed: !r.allowed } })
    await fetchRoutes()
    alert('更新成功')
  } catch (e) {
    alert('更新失败: ' + String(e?.message || e))
  }
}

onMounted(() => {
  fetchRoutes()
})


function saveKey() {
  adminKey.value = adminKeyInput.value
  if (adminKey.value) localStorage.setItem('admin_key', adminKey.value)
  fetchRoutes()
}

function clearKey() {
  adminKeyInput.value = ''
  adminKey.value = ''
  localStorage.removeItem('admin_key')
}


onMounted(() => {
  try {
    const saved = typeof window !== 'undefined' ? localStorage.getItem('admin_key') : null
    if (saved) {
      adminKeyInput.value = saved
      adminKey.value = saved
      fetchRoutes()
    }
  } catch (e) {}
})

</script>

<style scoped>
img { max-width: 100%; }
</style>
